package pl.dalkia.services.scanner.services.fetcher;

import java.io.BufferedReader;
import java.io.IOException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import pl.dalkia.services.scanner.services.exceptions.LackOfDatePatternException;
import pl.dalkia.services.scanner.services.matcher.DateConditionLogMatcher;
import pl.dalkia.services.scanner.services.matcher.SpecificConditionLogReverseMatcher;

public class ConfigurationFileFetcher implements Fetchable {

	private static final Logger log = LoggerFactory.getLogger(ConfigurationFileFetcher.class);
	
	private BufferedReader bufferedReader;

	
	public ConfigurationFileFetcher(BufferedReader fileBufferedReader){
		this.bufferedReader = fileBufferedReader;
	}
	
	@Override
	public Configuration fetch() throws LackOfDatePatternException {
		Configuration resultConfiguration = readDatePattern();
		resultConfiguration = readPossibleSpecificPatterns(resultConfiguration);
		
		log.info(String.format("Applied date and specific pattern(s):\n\n%1$s ", resultConfiguration.toString()));
		
		return resultConfiguration;
	}

	
	private Configuration readDatePattern() throws LackOfDatePatternException {
		String potentialDatePattern = null;
		Configuration resultConfiguration = null;
		while ( isFetchedLineEligible(potentialDatePattern = getLine()) ) {
			resultConfiguration = new Configuration(new DateConditionLogMatcher(potentialDatePattern));
			break;
		}
		
		if (resultConfiguration != null){
			return resultConfiguration;
		}
		throw new LackOfDatePatternException("Lack of date pattern in configuration file");
	}

	
	private Configuration readPossibleSpecificPatterns(Configuration resultConfiguration) {
		String potentialSpecificPatterns = null;
		while (isFetchedLineEligible(potentialSpecificPatterns = getLine())) {
			resultConfiguration.addSpecificPattern(new SpecificConditionLogReverseMatcher(potentialSpecificPatterns));
		}
		closeConnection();
		return resultConfiguration;
	}	


	private String getLine(){
		String inputLine = null;
		try {
			inputLine = bufferedReader.readLine();
		} catch (IOException e) {
			log.error("Unable to read from file.");
			System.exit(1);
		} 
		return inputLine;
	}
	
	
	private boolean isFetchedLineEligible(String potentialSpecificPatterns){
		return !(  potentialSpecificPatterns == null 
				|| potentialSpecificPatterns.charAt(0) == '#'
				|| potentialSpecificPatterns.equals("")  );
	}
	
	private void closeConnection(){
		try {
			bufferedReader.close();
		} catch (IOException e) {
//			throw new RuntimeException("Unable to close file propertly.", e);
			log.error("Unable to close file propertly.");
			System.exit(1);
		}
	}
	
}
